import 'dart:async';
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import '../../../../components/log_utils.dart';
import '../../../../routers/router_path.dart';
import '../../../../services/common/common_services.dart';
import '../../../../services/site/site_services.dart';
import 'models/service_provider_model.dart';
import 'models/site_detail_model.dart';

class SiteSettingBaseInfoController extends GetxController {
  // List<String> topTitleList = [ResKey.installManu.tr, '站点名称', '上线时间', '站点地址'];
  List<String> topTitleList = [
    ResKey.installManu.tr,
    ResKey.siteName.tr,
    ResKey.operationTime.tr,
    ResKey.siteAddress.tr,
  ];
  List<String> topDetailList = [];
  List<String> middleTitleList = [
    ResKey.siteBaseInfoVoltageClasses.tr,
    ResKey.siteBaseInfoTransformCapacity.tr,
    ResKey.siteBaseInfoPhotovoltaicCapacity.tr,
    ResKey.siteBaseInfoEnergyCapacity.tr,
    ResKey.siteBaseInfoEnergyPower.tr,
    ResKey.siteBaseInfoChargePower.tr,
    // '电压等级',
    // '变压器容量',
    // '光伏总容量',
    // '储能总容量',
    // '储能额定功率',
    // '充电桩总功率',
  ];
  List<String> middleDetailList = [];
  int siteId = 1;

  /// 站点服务
  SiteServices siteServices = Get.put(SiteServices());
  final CommonServices uploadServices = Get.put(CommonServices());
  SiteDetailModel detailModel = SiteDetailModel();
  bool isEnableEdit = false;
  bool btnCanClick = false;

  final TextEditingController installerController = TextEditingController();
  final TextEditingController siteNameController = TextEditingController();
  final TextEditingController timeController = TextEditingController();

  final TextEditingController siteAddressController = TextEditingController();

  final TextEditingController voltageLevelController = TextEditingController();
  final TextEditingController transformerCapacityController = TextEditingController();
  final TextEditingController photovoltaicCapacityController = TextEditingController();
  final TextEditingController energyCapacityController = TextEditingController();
  final TextEditingController energyPowerController = TextEditingController();
  final TextEditingController chargePowerController = TextEditingController();

  final TextEditingController remarkController = TextEditingController();
  final TextEditingController mapController = TextEditingController();

  ///站点图片列表
  List<String> deviceImageList = [];
  List<TextEditingController> middleControllerList = [];
  List<String> middleUnitList = ['kV','kVA','kWp','kWh','kW','kW',];
  ///站点logo
  String logoString = '';
  num longitude = 113.997026; //经度
  num latitude = 22.604063; //维纬度
  int pageNum = 1;
  int pageSize = 1000;
  bool isShowInstalling = false;
  int total = 100;
  bool isCanSubmit = false;
  final RefreshController refreshController = RefreshController();
  List<ServiceProviderModel> deviceInstallerList = [];
  List<ServiceProviderModel> selectedInstallerList = [];
  List<dynamic> orgsList = []; //选择的所有站点的集合
  num? adcode;
  bool isOwner = false; //是否是业主 如果是业主业，编辑基本信息时，安装商字段置灰无法编辑，右侧按钮去掉。
  List<String> mapList = [ResKey.aMap.tr, ResKey.googleMaps.tr];
  int selectedMapIndex = 0; //0为高德 1为谷歌
  @override
  void onInit() {
    super.onInit();
    middleControllerList = [
      voltageLevelController,transformerCapacityController,photovoltaicCapacityController,
      energyCapacityController,energyPowerController,chargePowerController
    ];
    var arguments = Get.arguments;
    Log.d('arguments==$arguments');
    mapController.text = mapList[selectedMapIndex];
    timeController.text = '--';
    if (arguments != null && arguments['siteId'] != null) {
      siteId = arguments['siteId'];
      getSiteDetail(arguments['siteId']);
    }
    if (UserEntityManager().roleID != null &&
        UserEntityManager().roleID == RoleType.owner.value) {
      isOwner = true;
    }
    // Log.d('isOwner===' + UserEntityManager().roleID.toString());
  }

  checkoutCanCommit() {
    if (installerController.text.isNotEmpty &&
        siteNameController.text.isNotEmpty &&
        siteAddressController.text.isNotEmpty) {
      isCanSubmit = true;
    } else {
      isCanSubmit = false;
    }
    update();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  void removeImageList(int index) {
    deviceImageList.removeAt(index);
    update();
  }

  getSiteDetail(int siteId) async {
    showLoading(toast: ResKey.loading.tr);
    var result =
        await siteServices.getSiteDetail({'siteId': siteId}, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    detailModel = SiteDetailModel.fromJson(result);
    _setInitData();
    checkoutCanCommit();
    update();
  }

  _setInitData() {
    if (detailModel.orgs != null && detailModel.orgs!.isNotEmpty) {
      if (detailModel.orgs!.length == 1) {
        installerController.text = detailModel.orgs![0].orgName.toString();
      } else {
        installerController.text =
            '${detailModel.orgs![0].orgName.toString()}...';
      }
    } else {
      topDetailList.add('');
    }
    siteNameController.text = detailModel.name ?? '';
    timeController.text = detailModel.deliveryTime ?? '--';
    siteAddressController.text = detailModel.address ?? '';

    voltageLevelController.text = detailModel.voltageClass != null
        ? ('${detailModel.voltageClass!}')
        : '';
    transformerCapacityController.text = detailModel.transformerCapacity != null
        ? ('${detailModel.transformerCapacity!}')
        : '';
    photovoltaicCapacityController.text =
        detailModel.photovoltaicInstalledCapacity != null
            ? ('${detailModel.photovoltaicInstalledCapacity!}')
            : '';
    energyCapacityController.text = detailModel.energyStorageCapacity != null
        ? ('${detailModel.energyStorageCapacity!}')
        : '';
    energyPowerController.text = detailModel.energyStoragePower != null
        ? ('${detailModel.energyStoragePower!}')
        : '';
    chargePowerController.text = detailModel.chargingStationCapacity != null
        ? ('${detailModel.chargingStationCapacity!}')
        : '';
    if (detailModel.photos != null && detailModel.photos!.isNotEmpty) {
      deviceImageList = detailModel.photos!.split(',');
    }
    if (detailModel.logo != null && detailModel.logo!.isNotEmpty) {
      logoString = detailModel.logo!;
    }
    remarkController.text = detailModel.remarks ?? '';
    if (detailModel.longitude != null) {
      longitude = detailModel.longitude!;
    }
    if (detailModel.latitude != null) {
      latitude = detailModel.latitude!;
    }
    if (detailModel.adcode != null) {
      adcode = detailModel.adcode!;
    }
    if (detailModel.map != null) {
      selectedMapIndex = detailModel.map!;
      if (selectedMapIndex < mapList.length) {
        mapController.text = mapList[selectedMapIndex];
      }
    }
  }

  ///跳转到地图页面
  void gotoMap() {
    Get.toNamed(RouterPath.amapPage, arguments: {
      'longitude': longitude,
      'latitude': latitude,
      'address': siteAddressController.text,
      'mapType': selectedMapIndex,
    })?.then((value) {
      if (value is AmapPoi) {
        longitude = value.longitude;
        latitude = value.latitude;
        if (value.adcode != null) {
          adcode = num.parse(value.adcode!);
        }
        siteAddressController.text = value.formattedAddress.toString();
        checkoutCanCommit();
      }
    });
  }

  ///选择地图类型
  chooseMapType(BuildContext context) {
    showDialog(
        context: context,
        builder: (_) => StatefulBuilder(
              builder: (context, state) {
                return BrnSingleSelectDialogWidget(
                    isClose: true,
                    title: ResKey.selectMapsType.tr,
                    conditions: mapList,
                    checkedItem: selectedMapIndex == -1
                        ? null
                        : mapList[selectedMapIndex],
                    submitText: ResKey.sure.tr,
                    isCustomFollowScroll: true,
                    themeData: BrnDialogConfig(
                        dialogWidth: 300.w,
                        contentTextStyle: BrnTextStyle(fontSize: 16.sp)),
                    onItemClick: (BuildContext context, int index) {
                      selectedMapIndex = index;
                      mapController.text = mapList[selectedMapIndex];
                      update();
                    },
                    onSubmitClick: (data) {
                      update();
                    });
              },
            ));
  }

  ///点击编辑按钮
  void edit() {
    isEnableEdit = !isEnableEdit;
    update();
  }

  ///展示安装商弹窗
  showInstaller() {
    isShowInstalling = true;
    update();

    if (deviceInstallerList.isEmpty) {
      getInstaller();
    }
  }

  ///选择好安装商,点击确认按钮
  chooseInstaller() {
    isShowInstalling = false;
    selectedInstallerList.clear();
    for (var element in deviceInstallerList) {
      if (element.isSelected != null && element.isSelected! == true) {
        selectedInstallerList.add(element);
      }
    }
    if (selectedInstallerList.isNotEmpty) {
      if (selectedInstallerList.length == 1) {
        installerController.text = selectedInstallerList[0].orgName.toString();
      } else {
        installerController.text =
            '${selectedInstallerList[0].orgName.toString()}...';
      }
    }
    if (selectedInstallerList.isNotEmpty) {
      orgsList.clear();
      for (var element in selectedInstallerList) {
        orgsList.add({'orgId': element.orgId});
      }
    }
    Log.d(
        'selectedInstallerList=111=' + selectedInstallerList.length.toString());

    update();
  }

  ///隐藏
  hiddenInstaller() {
    isShowInstalling = false;
    update();
  }

  ///请求获取安装商列表
  Future<dynamic> getInstaller() async {
    var params = {'current': pageNum, 'pageSize': pageSize};
    var result =
        await siteServices.getInstallProvideList(params, onError: (error) {
      refreshController.refreshCompleted();
      refreshController.loadComplete();
      handleException(error);
      dismissLoading();
      return false;
    });
    refreshController.refreshCompleted();
    refreshController.loadComplete();
    if (result != null && result['list'] != null) {
      var resultList = result['list'];
      List<ServiceProviderModel> tempList = [];
      resultList
          .forEach((item) => tempList.add(ServiceProviderModel.fromJson(item)));
      if (pageNum == 1) {
        deviceInstallerList.clear();
      }

      deviceInstallerList.addAll(tempList);
      if (deviceInstallerList.length >= result['total']) {
        refreshController.loadNoData();
      }
    }
    if (detailModel.orgs != null) {
      List<num> list = detailModel.orgs!.map((e) => e.orgId ?? 1).toList();
      Log.d('list==' + list.toString());

      for (var element in deviceInstallerList) {
        if (element.orgId != null && list.contains(element.orgId)) {
          element.isSelected = true;
        } else {
          element.isSelected = false;
        }
      }
    }
    update();
  }

  Future refreshData({isLoading = false}) async {
    pageNum = 1;
    await getInstaller();
  }

  Future loadMoreData() async {
    pageNum++;
    await getInstaller();
  }

  ///取消编辑
  void cancelEdit() {
    Log.d('cancelEdits');
    isEnableEdit = false;
    _setInitData(); //取消编辑重置数据为第一次请求数据
    update();
  }

  Future<void> save() async {
    String imageString = deviceImageList.join(',');
    var params = {
      'siteId': siteId,
      'name': siteNameController.text ?? '',
      'address': siteAddressController.text ?? '',
      'voltageClass': voltageLevelController.text ?? 0, //电压等级
      'transformerCapacity': transformerCapacityController.text ?? '', //变压器容量
      'photovoltaicInstalledCapacity':
          photovoltaicCapacityController.text ?? '', //光伏装机量
      'energyStoragePower': energyPowerController.text ?? '', //储能额定功率
      'energyStorageCapacity': energyCapacityController.text ?? '', //储能容量
      'chargingStationCapacity': chargePowerController.text ?? '', //充电桩装机量
      'photos': imageString,
      'remarks': remarkController.text ?? '',
      'latitude': latitude,
      'longitude': longitude,
      'logo': logoString,
      'orgs': orgsList,
      'map':selectedMapIndex,
    };
    if(adcode != null){
      params['adcode']= adcode!;
    }
    Log.d('params==$params');
    showLoading(toast: ResKey.loading.tr);
    var result = await siteServices.editSiteInfo(params, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      Get.back(result: true);
    }
  }
}
